# -*- coding: utf-8 -*-
import os,logging
from functools import wraps
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import setting

from model import ShareCategory,ShareLink,ShareCategoryLink,_today


def requires_admin(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.is_login:
            self.redirect(users.create_login_url(self.request.uri))
            return
        elif not (self.is_admin
            or self.author):
            return self.error(403)
        else:
            return method(self, *args, **kwargs)
    return wrapper

class BaseRequestHandler(webapp.RequestHandler):
    def __init__(self):
        pass

    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)

        # categories
        categories = ShareCategory.all()
        categories.order('-name')

        self.login_user = users.get_current_user()
        self.is_login = (self.login_user != None)
        self.loginurl=users.create_login_url(self.request.uri)
        self.logouturl=users.create_logout_url(self.request.uri)
        self.is_admin = users.is_current_user_admin()

        self.template_values = {'self':self,'sub_title':setting.SUBTITLE,'title':setting.TITLE,'categories':categories}

    def get_render(self,template_file,values):
        self.template_values.update(values)
        return template.render(template_file,self.template_values)

    def render(self,template_file,values):
        html=self.get_render(template_file,values)
        self.response.out.write(html)

    def write(self, s):
        self.response.out.write(s)

    def login(self,redirect_url='/'):
        if self.is_login:
            return True
        else:
            self.redirect(users.create_login_url(redirect_url))
        return False

    def logout(self, redirect_url='/'):
        if self.is_login:
            self.redirect(users.create_logout_url(redirect_url))
        else:
            return True
        return False

    def error_404(self):
        error_page(req, "404")
    
    def error_page(self, msg='oops'):        
        values={
            'error_msg':msg,
        }
        self.render("views/white/error.html",values)